package com.laoxu.java.multithread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 *
 * 请使用多线程处理大数据量for循环中处理数据返回处理结果
 *
 *
 */
public class MultiThreadedForLoop {

    public static void main(String[] args) throws Exception {
        int dataSize = 1000000; // 假设有100万个数据需要处理
        List<Integer> data = new ArrayList<>();
        for (int i = 0; i < dataSize; i++) {
            data.add(i);
        }

        int threadCount = 4; // 使用4个线程处理数据
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        List<Future<Integer>> futures = new ArrayList<>();

        int chunkSize = dataSize / threadCount;
        for (int i = 0; i < threadCount; i++) {
            int start = i * chunkSize;
            int end = (i + 1) * chunkSize;
            if (i == threadCount - 1) {
                end = dataSize; // 最后一个线程处理剩余的数据
            }
            Future<Integer> future = executorService.submit(new DataProcessor(data, start, end));
            futures.add(future);
        }

        int totalResult = 0;
        for (Future<Integer> future : futures) {
            totalResult += future.get();
        }

        System.out.println("处理结果： " + totalResult);
        executorService.shutdown();
    }

    static class DataProcessor implements Callable<Integer> {
        private List<Integer> data;
        private int start;
        private int end;

        public DataProcessor(List<Integer> data, int start, int end) {
            this.data = data;
            this.start = start;
            this.end = end;
        }

        @Override
        public Integer call() {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += data.get(i);
            }
            return sum;
        }
    }
}
